package com.casa.POI.dianping;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;


public abstract class Executor implements Time, Counter {
	
	private long startTime;
	private int counter;

	public String getPromptString() {
		String name = this.getClass().getName();
		int index = name.lastIndexOf('.');
		if (index != -1) {
			name = name.substring(index + 1);
		}
		index = name.lastIndexOf("Executor");
		if (index != -1) {
			name = name.substring(0, index);
		}
		String[] values = name.split("(?<!^)(?=[A-Z])");
		List<String> list = new ArrayList<String>();
		for (String value : values)
			list.add(value.toLowerCase());
		return StringUtils.join(list, ' ');
	}
	
	public void execute() {
		this.setStartTime(System.currentTimeMillis() / 1000);
	}
	
	@Override
	public long getStartTime() {
		return this.startTime;
	}

	public void setStartTime(long startTime) {
		this.startTime = startTime;
	}
	
	@Override
	public long getElapsedTime() {
		return TimeUtils.getElapsedTime(getStartTime());
	}
	
	public String getElapsedTimeString() {
		return TimeUtils.getTimeString(getElapsedTime());
	}
	
	@Override
	public synchronized int getCounter() {
		return this.counter;
	}
	
	@Override
	public synchronized void increaseCounter() {
		this.counter++;
	}
	
	public void printStatus(String status) {
		increaseCounter();
		String counterTime = String.format("%d %s", this.getCounter(), TimeUtils.getGlobalElapsedTimeString());
		int length = counterTime.length();
		String format = String.format("%%-%ds%%%ds", ConfigurationManager.getInstance().getConsoleCols() - length, length);
		Console.rewrite(String.format(format, status, counterTime));
	}
	
	public void printStatus(String format, Object... args) {
		this.printStatus(String.format(format, args));
	}
	
}
